package com.watchthelan.web.schedule.event;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.SchedulerException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.watchthelan.domain.Administrator;
import com.watchthelan.domain.Event;
import com.watchthelan.domain.Server;
import com.watchthelan.service.administrator.AdministratorManager;
import com.watchthelan.service.schedule.event.EventManager;
import com.watchthelan.service.server.ServerManager;

public class EventAddController extends SimpleFormController {
protected final Log logger = LogFactory.getLog(getClass());
	
	private EventManager eventManager;
	private ServerManager serverManager;
	private AdministratorManager administratorManager;
	
	public ModelAndView onSubmit(Object command)
	throws ServletException {
		Event event = (Event) command;
		eventManager.addEvent(event);
		
		logger.info("added event " + event);
		try {
		eventManager.scheduleEvent(event);
		} catch (SchedulerException e) {
			logger.info("failed to schedule event");
		}

		return new ModelAndView(new RedirectView(getSuccessView()));
	}

	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		Event event = new Event();
		String adminUsername = (String)request.getSession().getAttribute("administrator");
		Administrator admin = administratorManager.getAdministratorByUsername(adminUsername);
		event.setServers(serverManager.getServersOwnedBy(admin.getId()));
		event.setAdministrator(admin.getId());
		return event;
	}	

	public EventManager getEventManager() {
		return eventManager;
	}

	public void setEventManager(EventManager eventManager) {
		this.eventManager = eventManager;
	}

	public ServerManager getServerManager() {
		return serverManager;
	}

	public void setServerManager(ServerManager serverManager) {
		this.serverManager = serverManager;
	}

	public AdministratorManager getAdministratorManager() {
		return administratorManager;
	}

	public void setAdministratorManager(AdministratorManager administratorManager) {
		this.administratorManager = administratorManager;
	}

}
